package com.lyn.pluginbazaar.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lyn.pluginbazaar.dao.user.User;
import com.lyn.pluginbazaar.entity.Result;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class TokenUtil {

    public static String getToken(User user) {
        return DesUtil.getInstance().encrypt(JSONObject.toJSONString(user));
    }

    public static void setToken(HttpServletResponse response, String token) {
        response.addCookie(new Cookie("token", token));
    }

    public static User tokenToUser(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("token")) {
                String value = cookie.getValue();
                String decrypt = DesUtil.getInstance().decrypt(value);
                return JSONObject.toJavaObject(JSON.parseObject(decrypt), User.class);
            }
        }
        return null;
    }

    public static boolean checkToken(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            returnResult( "请登录!", response);
            return false;
        }
        String token = null;
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("token")) {
                token = cookie.getValue();
            }
        }
        if (CheckUtil.isEmpty(token)) {
            returnResult("请登录!", response);
            return false;
        }
        if (!RedisUtil.getInstance().hasKey(token)) {
            returnResult("请登录!", response);
            return false;
        }
        String decrypt = DesUtil.getInstance().decrypt(token);
        if (CheckUtil.isEmpty(decrypt)) {
            returnResult("请登录!", response);
            return false;
        }
        User user = JSONObject.toJavaObject(JSON.parseObject(decrypt), User.class);
        if (user == null) {
            returnResult("请登录!", response);
        } else {
            RedisUtil.getInstance().set(token, token, 60 * 60);
        }
        return user != null;
    }

    private static void returnResult(final String msg, HttpServletResponse response) {
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.append(JSON.toJSONString(Result.NOT_LOGGED_IN(msg)));
            writer.flush();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
